package com.zzyl.job;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AlertJob {

    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AlertDataService alertDataService;

    @Scheduled(cron="0/6 * * * * ?  ")
    public void obtainItOnAScheduledBasis(){
        //获取所有规则
        List<AlertRuleVo> allAlertRule = alertDataMapper.getAllAlertRule();

        //如果规则为空就直接结束
        if (allAlertRule.isEmpty()) {
            return;
        }

        //不为空则查询redis上所有设备的数据
        String allDeviceData = redisTemplate.opsForValue().get(CacheConstants.STORE_HEALTH_DATA);

        //redis中数据为空直接退出
        if (StrUtil.isBlank(allDeviceData)) {
            return;
        }
        //对redis中的数据进行处理
        List<DeviceDataVo> allDeviceDatalist = JSONUtil.toList(allDeviceData, DeviceDataVo.class);

        //每一条数据匹配规则
        allDeviceDatalist.forEach(deviceDataVo -> alertDataService.alertFilter(deviceDataVo));
    }
}
